class PhotosController < ApplicationController
  before_action :authenticate_user!, only: [:new, :edit, :create, :update, :destroy]
  skip_before_action :verify_authenticity_token, only: [:create]
  before_action :set_photo, only: [:show]
  before_action :set_photo_for_current_user, only: [:edit, :update, :destroy]

  # GET /photos
  # GET /photos.json
  def index
    page = params[:page] || 1
    per = params[:per] || 20
    @photos = Photo.all.page(page).per(per)
  end

  # GET /photos/1
  # GET /photos/1.json
  def show
  end

  # GET /photos/new
  def new
    @photo = Photo.new
  end

  # GET /photos/1/edit
  def edit
  end

  # POST /photos
  # POST /photos.json
  def create
    @photo = Photo.new(image: params['upload_file'])
    @photo.user_id = current_user.id
    if @photo.save!
      render json: {files: [@photo.to_jq_upload]}, status: :created
    else
      render json: @photo.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /photos/1
  # PATCH/PUT /photos/1.json
  def update
    respond_to do |format|
      if @photo.update(photo_params)
        format.html { redirect_to @photo, notice: 'Photo was successfully updated.' }
        format.json { render :show, status: :ok, location: @photo }
      else
        format.html { render :edit }
        format.json { render json: @photo.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /photos/1
  # DELETE /photos/1.json
  def destroy
    @photo.destroy
    respond_to do |format|
      format.html { redirect_to photos_url, notice: 'Photo was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private


  def set_photo_for_current_user
    @photo = current_user.photos.find_by(slug: params[:slug])
    raise ActiveRecord::RecordNotFound if @photo.blank?
  end

  def set_photo
    @photo = Photo.find_by(slug: params[:slug])
    raise ActiveRecord::RecordNotFound if @photo.blank?
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def photo_params
    params.require(:photo).permit(:image)
  end
end
